package com.my_test.webmagic.config;

import com.my_test.webmagic.webmagic_modules.SearchRedisScheduler;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.JedisPool;
import us.codecraft.webmagic.scheduler.RedisScheduler;

import java.net.InetAddress;

/**
 * @author zhangyalin@act-telecom.com
 * @since 2019-05-24 9:33
 **/
@Configuration
public class EsConfig {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * elk集群地址
     */
    @Value("${spring.es.host}")
    private String hostName;
    /**
     * 端口
     */
    @Value("${spring.es.port}")
    private String port;
    /**
     * 集群名称
     */
    @Value("${spring.es.clusterName}")
    private String clusterName;

    /**
     * 连接池
     */
    @Value("${spring.es.poolSize}")
    private String poolSize;

    @Bean
    public TransportClient transportClient() {
        TransportClient transportClient = null;
        try {
            // 配置信息
            Settings esSetting = Settings.builder()
                    .put("cluster.name", clusterName)
                    .put("client.transport.sniff", true)//增加嗅探机制，找到ES集群
                    .put("thread_pool.search.size", Integer.valueOf(poolSize))//增加线程池个数，暂时设为5
                    .build();
            transportClient = new PreBuiltTransportClient(esSetting);
            InetSocketTransportAddress inetSocketTransportAddress = new InetSocketTransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port));
            transportClient.addTransportAddresses(inetSocketTransportAddress);

        } catch (Exception e) {
            logger.error("elasticsearch TransportClient create error!!!", e);
        }
        return transportClient;
    }

    @Bean
    public RedisScheduler redisScheduler(JedisPool jedisPool) {
        RedisScheduler redisScheduler = new RedisScheduler(jedisPool);
        return redisScheduler;
    }

    @Bean
    public SearchRedisScheduler searchRedisScheduler(JedisPool jedisPool) {
        SearchRedisScheduler searchRedisScheduler = new SearchRedisScheduler(jedisPool);
        return searchRedisScheduler;
    }
}
